/*
 * @Author: 红尘痴子
 * @Date: 2020-07-03 09:47:47
 * @LastEditTime: 2020-08-11 15:52:55
 * @LastEditors: 红尘痴子
 * @Description:
 * @FilePath: \miaomeimei\pages\syntheticPoster\syntheticPoster.js
 * @https://www.jiangcan95.com/
 */

let app = getApp();
Page({
	/**
	 * 页面的初始数据
	 */
	data: {
		show: 0, // 1:商品  2:活动  3:视频  4:个人
		bgimg: '', // 背景图
		username: '', //用户名称
		headerImg: '', // 用户头像
		qrcode: '', //二维码
		tsimg: '', // 提示图片
		invitationCd: '', // 邀请码
		evntNm: '', // 活动名称
		productTitl: '', //商品标题 20个字
		productTitl1: '', //商品标题1 判断超过20个字,就截取19个+...
		amtSymbol: '¥', //金额符号
		amt: '', //金额
		prompt: '长按识别小程序码访问', //分享商品提示
		prompt1: '', //分享商品提示
		myInvitationCd: '我的邀请码',
		myInvitationCd1: 'CED1024',
	},

	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad: function (options) {
		let that = this;
		wx.showLoading({
			title: '合成海报中',
			mask: true,
		});
		that.setData({
			show: options.type || 0,
		});
		that.wxaCode(options.id, options.page, options.type);
	},
	// 获取分享数据
	wxaCode(id, page, type) {
		let that = this;
		app.http({
			url: app.api.wxaCode,
			data: {
				id: id,
				page: page,
				type: type,
			},
		})
			.then((res) => {
				let data = res.data.data;
				if (data.nickname.length > 4) {
					that.setData({
						username: data.nickname.slice(0, 4) + '...',
					});
				} else {
					that.setData({
						username: data.nickname,
					});
				}
				that.setData({
					myInvitationCd1: data.code, //邀请码
					qrcode: data.qr_code, //二维码
					evntNm: data.title,
				});
				// 1:商品  2:活动  3:视频  4:个人
				if (that.data.show == 1) {
					that.setData({
						share: data.goods.cover,
						amt: data.goods.amount,
						productTitl: data.goods.title,
					});
					if (data.goods.title1) {
						if (data.goods.title1.length > 20) {
							that.setData({
								productTitl1:
									data.goods.title1.slice(0, 19) + '...',
							});
						} else {
							that.setData({
								productTitl1: data.goods.title1,
							});
						}
					}
				} else if (that.data.show == 2) {
					that.setData({
						share: data.group.share,
					});
				} else {
					that.setData({
						share: data.share_img,
					});
				}
				wx.getImageInfo({
					src: data.avatarurl,
					success(res) {
						that.setData({
							headerImg: res.path,
						});
						// 判断是否活动
						that.downloadBgImg(data.qr_code);
					},
					fail(err) {
						wx.showToast({
							title: '图片下载失败,请稍后再试!',
							icon: 'none',
							success: (res) => {
								setTimeout(() => {
									wx.hideLoading();
									wx.navigateBack({
										back: 1,
									});
								}, 2000);
							},
						});
					},
				});
			})
			.catch((err) => {});
	},
	/**
	 * 生命周期函数--监听页面显示
	 */
	onShow: function () {},
	// 下载背景图
	downloadBgImg(qrcode) {
		let that = this;
		let imgArr = [];
		// 判断是什么类型的  1-商品 2-活动 3-视频 4-个人
		if (that.data.show == 1) {
			imgArr = [
				{
					img:
						'https://miaommeis-1301812909.cos.ap-guangzhou.myqcloud.com/syntheticPoster/NqRlX4.png',
					name: 'bgimg',
				},
				{
					img: qrcode,
					name: 'qrcode',
				},
				{
					img: that.data.share,
					name: 'share',
				},
			];
		} else if (that.data.show == 2) {
			imgArr = [
				{
					img:
						'https://miaommeis-1301812909.cos.ap-guangzhou.myqcloud.com/syntheticPoster/NqRlX4.png',
					name: 'bgimg',
				},
				{
					img:
						'https://miaommeis-1301812909.cos.ap-guangzhou.myqcloud.com/syntheticPoster/NqRQcF.png',
					name: 'tsimg',
				},
				{
					img: qrcode,
					name: 'qrcode',
				},
				{
					img: that.data.share,
					name: 'share',
				},
			];
		} else {
			imgArr = [
				{
					img:
						'https://miaommeis-1301812909.cos.ap-guangzhou.myqcloud.com/syntheticPoster/NqRlX4.png',
					name: 'bgimg',
				},
				{
					img: qrcode,
					name: 'qrcode',
				},
				{
					img: that.data.share
						? that.data.share
						: 'https://miaommeis-1301812909.cos.ap-guangzhou.myqcloud.com/bg/invite-friends-bg.png',
					name: 'share',
				},
				{
					img:
						'https://miaommeis-1301812909.cos.ap-guangzhou.myqcloud.com/syntheticPoster/%E7%BC%96%E7%BB%84%203%402x.png',
					name: 'invitationCd',
				},
			];
		}
		const arr = imgArr.map((path) => {
			return new Promise((resolve, reject) => {
				wx.getImageInfo({
					src: path.img,
					success: (res) => {
						resolve({
							img: res.path,
							name: path.name,
						});
					},
					fail: (err) => {
						wx.showToast({
							title: '图片下载失败,请稍后再试!',
							icon: 'none',
							success: (res) => {
								setTimeout(() => {
									wx.hideLoading();
									wx.navigateBack({
										back: 1,
									});
								}, 2000);
							},
						});
						reject(err);
					},
				});
			});
		});
		Promise.all(arr).then((res) => {
			res.map((item) => {
				if (item.name == 'bgimg') {
					that.setData({
						bgimg: item.img,
					});
				} else if (item.name == 'tsimg') {
					that.setData({
						tsimg: item.img,
					});
				} else if (item.name == 'qrcode') {
					that.setData({
						qrcode: item.img,
					});
				} else if (item.name == 'share') {
					that.setData({
						share: item.img,
					});
				} else {
					that.setData({
						invitationCd: item.img,
					});
				}
			});
			wx.getSystemInfo({
				success(res) {
					var query = wx.createSelectorQuery();
					//判断是什么类型的  1-商品 2-活动 3-视频 4-个人
					if (that.data.show == 1) {
						that.setData({
							width: 338 * res.pixelRatio,
							height: 540 * res.pixelRatio,
							pixelRatio: res.pixelRatio,
						});
						query
							.select('#canvasPoster')
							.boundingClientRect((res) => {
								// 返回值包括画布的实际宽高
								that.drawImage(res);
							})
							.exec();
					} else {
						that.setData({
							width: 338 * res.pixelRatio,
							height: 488 * res.pixelRatio,
							pixelRatio: res.pixelRatio,
						});
						query
							.select('#canvasPoster')
							.boundingClientRect((res) => {
								// 返回值包括画布的实际宽高
								that.drawImage(res);
							})
							.exec();
					}
				},
			});
		});
	},
	// 合成图片
	drawImage(canvasAttrs) {
		let that = this;
		let ctx;
		ctx = wx.createCanvasContext('canvasPoster');
		var canvasW;
		var canvasH;
		var headerW;
		var headerX;
		var headerY;

		var productTitlX;
		var productTitlY;
		var productTitl1X;
		var productTitl1Y;
		var amtSymbolX;
		var amtSymbolY;
		var amtX;
		var amtY;
		var promptX;
		var promptY;

		var textX;
		var textY;
		var text1X;
		var text1Y;
		var productPicW;
		var productPicX;
		var productPicY;
		var promptPicW;
		var promptPicH;
		var promptPicX;
		var promptPicY;
		var qrcodeW;
		var qrcodeX;
		var qrcodeY;

		let myInvitationCdX;
		let myInvitationCdY;
		let myInvitationCd1X;
		let myInvitationCd1Y;

		canvasW = canvasAttrs.width; // 画布的真实宽度
		canvasH = canvasAttrs.height; //画布的真实高度
		// 头像和二维码大小都需要在规定大小的基础上放大像素比的比例后面都会 *this.systemInfo.pixelRatio
		if (that.data.show == 1) {
			headerW = 40 * that.data.pixelRatio; //头像宽
			headerX = 20 * that.data.pixelRatio; // 头像X值
			headerY = 20 * that.data.pixelRatio; // 头像Y值

			textX = 68 * that.data.pixelRatio; //名字X值
			textY = 46 * that.data.pixelRatio; //名字Y值

			text1X = 144 * that.data.pixelRatio; //活动标题X值
			text1Y = 46 * that.data.pixelRatio; //活动标题Y值
		} else {
			headerW = 40 * that.data.pixelRatio; //头像宽
			headerX = 20 * that.data.pixelRatio; // 头像X值
			headerY = 17 * that.data.pixelRatio; // 头像Y值

			textX = 68 * that.data.pixelRatio; //名字X值
			textY = 42 * that.data.pixelRatio; //名字Y值

			text1X = 144 * that.data.pixelRatio; //活动标题X值
			text1Y = 42 * that.data.pixelRatio; //活动标题Y值
		}
		// 商品
		if (that.data.show == 1) {
			productTitlX = 20 * that.data.pixelRatio; //商品标题X值
			productTitlY = 392 * that.data.pixelRatio; //商品标题Y值

			productTitl1X = 20 * that.data.pixelRatio; //商品标题1X值
			productTitl1Y = 412 * that.data.pixelRatio; //商品标题1Y值

			amtSymbolX = 20 * that.data.pixelRatio; //金额符号X值
			amtSymbolY = 462 * that.data.pixelRatio; //金额符号Y值

			amtX = 30 * that.data.pixelRatio; //金额X值
			amtY = 462 * that.data.pixelRatio; //金额Y值

			promptX = 20 * that.data.pixelRatio; //分享商品提示X值
			promptY = 492 * that.data.pixelRatio; //分享商品提示Y值
		}
		// 活动
		if (that.data.show == 2) {
			promptPicW = 144 * that.data.pixelRatio; //提示宽
			promptPicH = 58 * that.data.pixelRatio; //提示宽
			promptPicX = 20 * that.data.pixelRatio; //提示X值
			promptPicY = 397 * that.data.pixelRatio; //提示Y值
		}

		if (that.data.show == 4) {
			myInvitationCdX = 60 * that.data.pixelRatio; //我的邀请码X值
			myInvitationCdY = 420 * that.data.pixelRatio; //我的邀请码Y值

			myInvitationCd1X = 40 * that.data.pixelRatio; //我的邀请码X值
			myInvitationCd1Y = 450 * that.data.pixelRatio; //我的邀请码Y值

			promptPicW = 144 * that.data.pixelRatio; //提示宽
			promptPicH = 58 * that.data.pixelRatio; //提示宽
			promptPicX = 20 * that.data.pixelRatio; //提示X值
			promptPicY = 397 * that.data.pixelRatio; //提示Y值
		}

		productPicW = 295 * that.data.pixelRatio; //产品图宽
		productPicX = 20 * that.data.pixelRatio; //产品图X值
		productPicY = 69 * that.data.pixelRatio; //产品图Y值

		qrcodeW = 100 * that.data.pixelRatio; //二维码宽
		// 二维码 XY值
		if (that.data.show == 1) {
			qrcodeX = 215 * that.data.pixelRatio; //二维码X值
			qrcodeY = 428 * that.data.pixelRatio; //二维码Y值
		} else {
			qrcodeX = 215 * that.data.pixelRatio; //二维码X值
			qrcodeY = 376 * that.data.pixelRatio; //二维码Y值
		}
		// 填充背景
		ctx.drawImage(that.data.bgimg, 0, 0, canvasW, canvasH);
		ctx.save();

		// 绘制名字
		ctx.setFillStyle('#ef7d7d'); // 文字颜色：黑色
		ctx.setFontSize(40); // 文字字号：22px
		ctx.fillText(that.data.username, textX, textY); //开始绘制文本的 x/y 坐标位置（相对于画布）
		ctx.save();

		// 绘制活动标题
		ctx.setFillStyle('#000'); // 文字颜色：黑色
		ctx.setFontSize(40); // 文字字号：22px
		ctx.fillText(that.data.evntNm, text1X, text1Y); //开始绘制文本的 x/y 坐标位置（相对于画布）
		ctx.save();

		// 控制头像为圆形
		ctx.setStrokeStyle('rgba(0,0,0,.2)'); //设置线条颜色，如果不设置默认是黑色，头像四周会出现黑边框
		ctx.arc(
			headerX + headerW / 2,
			headerY + headerW / 2,
			headerW / 2,
			0,
			2 * Math.PI
		);
		//画完之后执行clip()方法，否则不会出现圆形效果
		ctx.clip();
		// 将头像画到画布上
		ctx.drawImage(that.data.headerImg, headerX, headerY, headerW, headerW);
		ctx.restore();
		ctx.save();

		// 绘制中间产品图
		ctx.drawImage(
			that.data.share,
			productPicX,
			productPicY,
			productPicW,
			productPicW
		);
		ctx.restore();
		ctx.save();

		// 绘制二维码
		ctx.drawImage(that.data.qrcode, qrcodeX, qrcodeY, qrcodeW, qrcodeW);
		ctx.restore();
		ctx.save();

		//绘制提示图片
		ctx.drawImage(
			that.data.tsimg,
			promptPicX,
			promptPicY,
			promptPicW,
			promptPicH
		);
		ctx.restore();
		ctx.save();
		if (that.data.show == 1) {
			ctx.setFillStyle('#000'); // 文字颜色
			ctx.setFontSize(44); // 文字字号：22px
			ctx.fillText(that.data.productTitl, productTitlX, productTitlY); //开始绘制文本的 x/y 坐标位置（相对于画布）
			ctx.save();

			ctx.setFillStyle('#000'); // 文字颜色
			ctx.setFontSize(44); // 文字字号：22px
			ctx.fillText(that.data.productTitl1, productTitl1X, productTitl1Y); //开始绘制文本的 x/y 坐标位置（相对于画布）
			ctx.save();

			ctx.setFillStyle('#ED5757'); // 文字颜色
			ctx.setFontSize(44); // 文字字号：22px
			ctx.fillText(that.data.amtSymbol, amtSymbolX, amtSymbolY); //开始绘制文本的 x/y 坐标位置（相对于画布）
			ctx.save();

			ctx.setFillStyle('#ED5757'); // 文字颜色
			ctx.setFontSize(70); // 文字字号：22px
			ctx.fillText(that.data.amt, amtX, amtY); //开始绘制文本的 x/y 坐标位置（相对于画布）
			ctx.save();

			ctx.setFillStyle('rgba(0,0,0,0.3)'); // 文字颜色
			ctx.setFontSize(40); // 文字字号：22px
			ctx.fillText(that.data.prompt, promptX, promptY); //开始绘制文本的 x/y 坐标位置（相对于画布）
			ctx.save();
		}
		if (that.data.show == 4) {
			ctx.setFillStyle('rgba(0,0,0,0.3)'); // 文字颜色
			ctx.setFontSize(40); // 文字字号：22px
			ctx.fillText(
				that.data.myInvitationCd,
				myInvitationCdX,
				myInvitationCdY
			); //开始绘制文本的 x/y 坐标位置（相对于画布）
			ctx.save();

			ctx.setFillStyle('#000'); // 文字颜色
			ctx.setFontSize(70); // 文字字号：22px
			ctx.fillText(
				that.data.myInvitationCd1,
				myInvitationCd1X,
				myInvitationCd1Y
			); //开始绘制文本的 x/y 坐标位置（相对于画布）
			ctx.save();

			ctx.drawImage(
				that.data.invitationCd,
				promptPicX,
				promptPicY,
				promptPicW,
				promptPicH
			);
			ctx.restore();
			ctx.save();
		}

		ctx.draw();
		setTimeout(() => {
			//下面的13以及减26推测是因为在写样式的时候写了固定的zoom: 50%而没有用像素比缩放导致的黑边，所以在生成时进行了适当的缩小生成，这个大家可以自行尝试
			wx.canvasToTempFilePath({
				canvasId: 'canvasPoster',
				x: 13,
				y: 13,
				width: canvasW - 26,
				height: canvasH - 26,
				destWidth: canvasW - 26,
				destHeight: canvasH - 26,
				success: (res) => {
					// that.poster = res.tempFilePath;
					that.setData({
						poster: res.tempFilePath,
					});

					wx.hideLoading();
				},
			});
		}, 200);
	},
	// 预览图片
	previewImg() {
		let that = this;
		if (that.data.poster) {
			//预览图片，预览后可长按保存或者分享给朋友
			wx.previewImage({
				urls: [that.data.poster],
			});
		}
	},
	// 保存图片
	savePoster() {
		let that = this;
		if (that.data.poster) {
			wx.saveImageToPhotosAlbum({
				filePath: that.data.poster,
				success: (result) => {
					wx.showToast({
						title: '海报已保存，快去分享给好友吧。',
						icon: 'none',
					});
				},
			});
		}
	},
});
